const position = require("../models/mongooseModel");
const moment = require("moment")

//es6 await等待的意思 但是它只能用在异步函数里面
//es6 async 可以把函数变为异步函数

const positionAdd = async (req, res) => {
    console.log("进来了")
    //设置一个自增的字段 先查找 用查找回来的数组length+1

    let tokenId = await position.find();//[]
    // 下载moment中间件moment().format('MMMM Do YYYY, h:mm:ss a')
    req.body.createTime = moment().format('MMMM Do YYYY, h:mm:ss a');
    // res.set("Content-Type", "application/json")
    // console.log("结果是", tokenId)
    console.log(req.body);

    //这个req.imgAddress是前面upload中间件携带过来的属性
    req.body.companyLogo = req.imgAddress;
    req.body.tokenId = tokenId.length + 1;
    const result = await position.save(req.body); //等待model层储存完返回的结果
    console.log("结果是" + result);
    if (result !== "false") {
        const data = JSON.stringify({ status: true, msg: result })
        // res.render("success", { data: data })
        res.send(data)
    } else {
        const message = JSON.stringify({ status: false, msg: "保存失败" })

        // res.render("error", message)
        res.send(message)
    }
}
//查找
const positionFind = async (req, res) => {
    req.query.count = req.query.count || 5;
    let query = {
        tokenId: { tokenId: req.query.tokenId || "" },
        key: req.query.key ? { companyName: new RegExp(req.query.key) } : "",
        page: (req.query.page - 1) * req.query.count || 0,
        count: req.query.count - 0
    }
    let result = await position.find(query);
    //查询总数量

    let count = await position.find();
    count = count.length;
    res.setHeader('Content-Type', 'application/json;charset=utf8')
    res.send({ count: count, result });
}

//删除 传输tokenId给Model层

const positionDel = async (req, res) => {
    // 删除通过get的方式删除
    const tokenId = req.query.tokenId
    const result = await position.del(tokenId)
    if (result.n !== 0) {
        res.send({ status: true, message: "删除成功" })
    } else {
        res.send({ status: false, message: "删除失败" })
    }

}
//更新
const positionUpdate = async (req, res) => {
    console.log(req.body);
    //判断 如果没有上传图片就不要给req.body添加companyLogo 这样数据库就不会对companyLogo进行更新
    if (req.imgAddress) {
        req.body.companyLogo = req.imgAddress;
    }
    const query = req.body.tokenId;
    console.log(query)
    const result = await position.update(query, req.body)
    if (result) {
        res.send({ status: true, message: "更新成功" })
    } else {
        res.send({ status: false, message: "更新失败" })
    }
}
module.exports = { positionAdd, positionFind, positionDel, positionUpdate }















// const positionDel = async (req, res) => {
//     console.log(req.query.tokenId)
//     let result = await position.del(req.query.tokenId)
//     if (result) {
//         res.send({ status: true, msg: "删除成功" })
//     } else {
//         res.send({ status: false, msg: "删除失败" })
//     }
// }
